


/* -------------------------- AES alogrithm using password key -----------------------------------*/


    import java.security.spec.AlgorithmParameterSpec;
    import javax.crypto.Cipher;
    import javax.crypto.spec.IvParameterSpec;
    import javax.crypto.spec.SecretKeySpec;
    import sun.misc.BASE64Encoder;
    import sun.misc.BASE64Decoder;


  public class AESCrypt 
  {
	  Cipher cipher; 
	  public String input;
	  public String strPassword; 
	  public SecretKeySpec key;
	  public static final String TRANSPARENT_KEY = " ";
	  
	  
	  public AESCrypt(String input, String strPassword)
	  {
		  if(strPassword.length() < 17)
		  {
		  		while(strPassword.length() != 16)
		  		{
		  			strPassword = strPassword + AESCrypt.TRANSPARENT_KEY;	
		  		}	
		  }
		  else if(strPassword.length()>= 17)
		  {
		  		strPassword = strPassword.substring(0, 16);
		  }
		  
		  this.input=input;
		  this.strPassword=strPassword;
	
	
		  this.key = new SecretKeySpec(strPassword.getBytes(), "AES");
	
	  }
	 // POUR CRYPTER
	  public String encrypt() throws Exception
	  {
	   		AlgorithmParameterSpec paramSpec = new IvParameterSpec(strPassword.getBytes()); 
	    
	   		this.cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
	
	      	cipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
	
	      	byte[] ecrypted = cipher.doFinal(input.getBytes());
	
	     	String output = new BASE64Encoder().encode(ecrypted);
	     
	    	return output;
	  }
		
		
		// DECRYPTER
	  public String decrypt() throws Exception
	  {
	  	    AlgorithmParameterSpec paramSpec = new IvParameterSpec(strPassword.getBytes()); 
	
	    	this.cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
	
	     	cipher.init(Cipher.DECRYPT_MODE, key, paramSpec);
	     	
	     	byte[] output =  new BASE64Decoder().decodeBuffer(input);
	     	
	     	byte[] decrypted = cipher.doFinal(output);
	
	    	String finalMessage = new String (decrypted);
	            
	        return finalMessage;
	  }
  }


  